#!/usr/bin/env python

# Copyright 2011 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#    http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import logging
import urllib

from google.appengine.api import memcache
import common
from lib import http
import model

__author__ = "Maciej Machulak"
__maintainer__ = "Maciej Machulak"
__email__ = "mmachulak@google.com"

__copyright__ = "Copyright 2011, Google Inc."
__license__ = "Apache License 2.0"
__version__ = "0.1"
__status__ = "Prototype"

__SESSION_ID = common.SESSION_ID

def __get_session_id(request):

    # Retrieve session id from the cookie
    try:
        session_id = request.cookies[__SESSION_ID]
    except KeyError:
        session_id = None
    return session_id

def __get_session(session_id = None):

    if session_id is None:
        return None

    # If session id present, then try to retrieve session from memcache
    session = memcache.get(session_id)
    if session is None:

        # If session not in memcache then try datastore
        logging.debug('session not found in memcache, trying datastore')
        session = model.Session.all().filter('id = ', session_id).get()

    return session


def login_required(registered = True):

    def inner_login_required(handler):

        """Requires that a user is logged in to be able to execute a method."""

        def check_login(self,*args):

            session_id = __get_session_id(self.request)

            logging.debug('session id: %s' % session_id)

            if session_id is None:
                logging.debug('session id is none - redirecting to main page')
                self.redirect('/?continue_to=' + urllib.quote_plus(self.request.url))
                return

            session = __get_session(session_id)

            logging.debug('session %s' % session)

            if session is None:
                logging.debug('session could not be retrieved from the database')
                self.response.headers.add_header(http.Header.set_cookie, __SESSION_ID + '=')
                logging.debug('deleting session cookie')
                self.redirect('/?continue_to=' + urllib.quote_plus(self.request.url))
                return
            if session.user is None:
                logging.debug('session present but user not associated')
                if registered:
                    raise AuthError('session found but user not present')
            else:
                logging.debug('user found and associated with an existing user')
                logging.debug('user has been logged in successfully')
                self.user = session.user
            logging.debug('session associated with the handler object')
            self.session = session
            handler(self,*args)
      
        return check_login

    return inner_login_required


 
def redirect_logged_user(location = '/'):
  
  def inner_redirect(handler):

      def check_user_status(self,*args):

          session_id = __get_session_id(self.request)

          if session_id:
              logging.debug('session id: %s' % session_id)

              session = __get_session(session_id)

              if session:

                  if session.user:

                      logging.debug('session for user %s' % session.user)
                      self.session = session
                      self.user = session.user
                      self.redirect(location)
                      return
              logging.debug('session could not be retrieved from the DB')
              self.response.headers.add_header(http.Header.set_cookie, __SESSION_ID + '=')
              logging.debug('deleting session cookie')
          handler(self,*args)
      
      return check_user_status
    
  return inner_redirect

class AuthError(Exception):

    """Raised when there is an error with with the authentication process."""
    
    def __init__(self, msg):
        Exception.__init__(self)
        self.msg = msg

    def __str__(self):
        return repr(self.msg) 
    
if __name__ == '__main__':
    pass